package pacman;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
@SuppressWarnings("serial")
public final class Pacman extends JFrame implements KeyListener,MouseListener,MouseMotionListener{
    public static int Score=0;//bien dung de luu diem so
    public static int HighScore;//luu diem cao
    public static int Width=520;//kich thuoc chieu ngang game
    public static int Height=710;//kich thuoc chieu rong

    //Hình ảnh trong GAME
    public Image backroundImg;//man hinh nen
    public Image backImg;
    public Image GameOverImg;//hinh anh khi thua
    public Image PausedImg;//tam dung game
    public Image LostImg;
    public Image WonImg;
    public Image DoorImg;
    public Image scaredWallImg;//
    public Image wallImgColum;
    public Image wallImgRow;
    public Image wallImgAngleA;
    public Image wallImgAngleB;
    public Image wallImgAngleC;
    public Image wallImgAngleD;
    public Image wallImgAngleRA;
    public Image wallImgAngleRB;
    public Image wallImgAngleRC;
    public Image wallImgAngleRD;
    public Image wallImgAngleR;
    
    public Image[][][] GHOST_IMG;
    public Image[][] PAC_IMG;
    public Image VAT_PHAM;
    public Image[] SCARED_GHOST;
    public Image[] SCARED_GHOST_RECOVERY;
    
    public static int NEW_GAME_IND;
    public Image[] NEW_GAME_IMG;
    //Player
    public static int TOA_DO_BAN_DAU_Px;
    public static int TOA_DO_BAN_DAU_Py;    
    public static int TOA_DO_HIEN_TAI_Px;
    public static int TOA_DO_HIEN_TAI_Py;
    public static int PmSpeed;   
    public static int Pdir;
    public static int NewKeydir;
    public static int Plives;   
    public static int PacAnimInd;
    public static int PacAnimCounter;
    public static int PacAnimDir;
    public static int PacisSuper;
    public static long PacSuperTime;
    public static int PacNormalSpeed;
    public static int PacSuperSpeed;
    public static int Pac_going_super;
    public static double PacLostTime;
    public static String GameStatus;
    public static int DoorX;
    public static int DoorY;
    public static Boolean stopit;
    public static int SoVatPham;
    public static int tmpDotCnt;
    public static int FirstLoad;
    public static int GhostX[];
    public static int GhostY[];
    public static int GhostDir[];
    public static int GhostAnimFrame[];
    public static int GhostAnimCnt[];
    public static int GhostRecoveryChangeCnt;
    public static int GhostRecoveryChange;
    public static int SO_GHOST_AN;
    public static Boolean anNgoc;// Kiểm tra ăn ngọc
    public static int GhostSpawn[][];
    public static int tmpGhostSpawn[][];    
    public static int GhostSpawnMax=0; 
    public static int DIEM_LEVEL=0;
     //mang dung de luu map
    public static char[][] level;//mang dung luu map
    public static DrawGame cnv;//lop myCanVasPanel
    public static Graphics2D score;
    public Pacman(){
        super("Pacman by Khanh Hoa & Kim D Son");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(400,10,Width,Height);
        LoadGraphics();
        cnv = new DrawGame(this);
        JPanel GamePanel = new JPanel();
        GamePanel.setLayout(new BorderLayout());
        GamePanel.add("Center",cnv);
        setContentPane(GamePanel);
        addKeyListener(this);
        addMouseMotionListener(this);
        addMouseListener(this);
    }
    public static void Khoitao(){
        Pdir=0;
        NewKeydir=0;
        PacNormalSpeed=4;
        PacSuperSpeed=6;
        PmSpeed=4;//toc do binh thuong cua pacman
        PacAnimInd=0;
        PacAnimCounter=0;
        PacAnimDir = 1;
        PacisSuper=0;
        PacSuperTime=0;
        Pac_going_super=0;
        java.awt.Dimension screenInfo = Toolkit.getDefaultToolkit().getScreenSize();
        FirstLoad=1;
        NEW_GAME_IND=0;
        if ((!"gameover".equals(GameStatus)) && (!"lost".equals(GameStatus))) {
            GameStatus="startup";
        }
        Plives = 3;
        SO_GHOST_AN=0;
        GhostRecoveryChangeCnt = 0;
        GhostRecoveryChange = 0;
        GhostX=new int[4];//khoi tao mang luu toa do 4 con ma
        GhostY=new int[4];
        GhostDir=new int[4];
        GhostAnimFrame=new int[4];
        GhostAnimCnt=new int[4];          
        for(int i=0;i<4;i++){
            GhostX[i]=0;
            GhostY[i]=0;
            GhostDir[i]=2;
            GhostAnimFrame[i]=0;
            GhostAnimCnt[i]=0;
        }
        anNgoc=false;
        LoadMap(); //load map tu file data roi luu vao level
    }
    @Override
    public void mouseClicked(MouseEvent evt) { 
        int x,y;
        x = evt.getX();
        y = evt.getY()-20;
        
        if ((x>340)&&(x<340+140)) {
            if ((y>637)&&(y<637+35)) {
                //Clicked Button
                GameStatus="ingame";
            }
        }
    }
    @Override
    public void mouseEntered(MouseEvent evt) { 
    }
    @Override
    public void mouseExited(MouseEvent evt) { 
    }
    @Override
    public void mousePressed(MouseEvent evt) { 
        int x,y;
        x = evt.getX();
        y = evt.getY()- 20;
        
        if ((x>340)&&(x<340+140)) {
            if ((y>637)&&(y<637+35)) {
                NEW_GAME_IND=2;
            }
        }
    }
    @Override
    public void mouseReleased(MouseEvent evt) { 
        NEW_GAME_IND=0;
    }
    @Override
    public void mouseDragged(MouseEvent evt) { 
    }
    @Override
    public void mouseMoved(MouseEvent evt) { 
        int x,y;
        x = evt.getX();
        y = evt.getY() - 20;
        
        if (NEW_GAME_IND!=2) {
            NEW_GAME_IND = 0;                
            if ((x>340)&&(x<340+140)) {
                if ((y>637)&&(y<637+35 )) {
                    //move over the button
                    NEW_GAME_IND=1;
                }
            } 
        }
    }   
    @Override
    public void keyReleased(KeyEvent evt) { 
    }
    @Override
    public void keyPressed(KeyEvent evt) { 
        int ckey;// dùng mã ASCII trong hệ thập phân
        ckey = evt.getKeyCode();
        if (ckey==38){
            NewKeydir=1; //di chuyen len
        }
        if (ckey==40){
            NewKeydir=3; //di chuyen xuong
        }
        if (ckey==37){
            NewKeydir=2; //di sang phai
        }
        if (ckey==39){
            NewKeydir=0; //sang trai
        }
        if (ckey==80){//tạm dừng game
            //P key
            if ("paused".equals(GameStatus)){
                GameStatus="ingame";
            } else {
                if("ingame".equals(GameStatus)){
                    GameStatus ="paused";
                }
            }
        }
        if(ckey==83){//xem điểm cao
            //S key
            int i = 0;  
            FileInputStream fin = null;
            String file = "";
            /*
            Scanner fileStream = new Scanner(fin);
            * 
            while(fileStream.hasNextLine()) {
                    file += fileStream.nextLine();
            }
            */
            try
            {
                fin = new FileInputStream("HighScores.txt");
            }
            catch(FileNotFoundException exc)
            {
                System.out.println("File is not Found");
                return;
            }
            catch(ArrayIndexOutOfBoundsException exc)
            {
                System.out.println(exc.toString());
                return;
            }
            
            do
            {
                try {
                    i=fin.read();
                } catch (IOException ex) {
                    Logger.getLogger(Pacman.class.getName()).log(Level.SEVERE, null, ex);
                }
                if(i!=-1){
                    System.out.print((char)i);
                    file+=(char)i;
                }
            }
            while(i!=-1);            
            // Xuất TextArea
            //Create GUI
            JFrame win = new JFrame("High Scores");
            JPanel pan = new JPanel();
            JTextArea area = new JTextArea();
            area.setColumns(2);
            area.setRows(6);
            area.setText(file);
            area.setCaretColor(Color.GREEN);
            area.setSelectedTextColor(Color.GREEN);
            area.setBackground(Color.BLUE);
            area.setForeground(Color.BLACK);
            pan.add(area);
            pan.setSize(200, 150);
            pan.setBackground(Color.BLACK);
            win.add(pan);
            win.setLocation(540,320);/////////
            win.setSize(230, 150);
            win.setVisible(true);
            win.setResizable(false);
            win.setLayout(new FlowLayout());  
            //
            
            try {
                 fin.close();
            } catch (IOException ex) {
                 Logger.getLogger(Pacman.class.getName()).log(Level.SEVERE, null, ex);
            }
                                 
        }   
        
        if (ckey==81){//thoat
            stopit=true; //Q key
            System.exit(0);
        }
    }
    @Override
    public void keyTyped(KeyEvent evt) {
    }
    public static void setupGhosts(){
        int tmpi=0;
        int tmpi2=0;
        
        tmpi2 = GhostSpawnMax-1;
        for (tmpi=0;tmpi<4;tmpi++){
            if (tmpi2<0){
                tmpi2=GhostSpawnMax-1;
            }
            if (tmpi2>-1){
                GhostX[tmpi]=GhostSpawn[tmpi2][0];
                GhostY[tmpi]=GhostSpawn[tmpi2][1];
                tmpi2 -= 1;
            }   
        }
    }
    public static void setupGhostSingle(int i){

        GhostX[i]=GhostSpawn[0][0];
        GhostY[i]=GhostSpawn[0][1];
    }
    public static void main(String[] args){
        int tmplives;
        Khoitao();  //
        HighScore=Diemso.LoadHighScore();
        Pacman frm = new Pacman(); // load window
        StartMusic();
        frm.setVisible(true);
        frm.setResizable(false);
        while(true){
            Khoitao();  //khoi tao bien
            stopit=false;
            tmplives=Plives;
            try{
                while(stopit==false){
                    Thread.sleep(35);
                    if (Sound.player.isRunning() ==false){
                        Sound.player.stop();
                        Sound.player.close();
                        StartMusic();
                    }
                    if ("ingame".equals(GameStatus)){
                        CheckKeys();//check Key de di chuyen pacman
                        MovePacman();//di chuyen pacman
                        AnimatePacMan();//kiem tra huong de ve
                        MoveGhosts();//di chuyen ma
                        CheckCollisions();//kiem tra xem co cham nhau hay khong de an
                    }
                    else
                    if ("lost".equals(GameStatus)){
                        if(2500<(System.currentTimeMillis()-PacLostTime)){
                            setupGhosts();
                            TOA_DO_HIEN_TAI_Px=TOA_DO_BAN_DAU_Px;
                            TOA_DO_HIEN_TAI_Py=TOA_DO_BAN_DAU_Py;
                            tmplives -= 1;
                            Plives=tmplives;
                            if (Plives==-1){
                                GameStatus="gameover";
                                Diemso.NewHighScore(Score,HighScore);
                                tmplives=3;
                                Khoitao();
                                setupGhosts();                              
                            } else {
                                GameStatus="ingame";
                            }                            
                        }
                   } 
                cnv.repaint();
                }
            } catch(InterruptedException e){}; 
        }
    } 
    
    public void drawScore(int x, int y){
        
    }
    //Xử lý trường hợp Pacman va chạm với Ghost
    public static void CheckCollisions(){
        int n=0,res=0,Ghostind=0;
        if (anNgoc==true){
                if (System.currentTimeMillis() - PacSuperTime >5000){
                    GhostRecoveryChangeCnt += 1;
                    if (GhostRecoveryChangeCnt >10){
                        GhostRecoveryChangeCnt = 0;
                        if (GhostRecoveryChange==1)
                            GhostRecoveryChange=0;
                        else
                            GhostRecoveryChange=1;
                    }
                }
        }
        Rectangle2D.Double Pc = new Rectangle2D.Double(TOA_DO_HIEN_TAI_Px+2,TOA_DO_HIEN_TAI_Py+2,20,20);
        for(n=0;n<4;n++){
            if (Pc.intersects(GhostX[n],GhostY[n],24,24)==true){
                res=1;

                Ghostind=n;
            }   
        }
        if(res==1){
            if(anNgoc==true){
                setupGhostSingle(Ghostind);
                SO_GHOST_AN += 1;
                if(SO_GHOST_AN==1) {
                    Score+= 200;
                }                    
                else 
                    if (SO_GHOST_AN==2) {
                    Score+= 400;
                }
                else 
                    if (SO_GHOST_AN==3) {
                    Score+= 800;
                }
                else {
                    Score+= 1600;
                }
            }
            else{  
                Sound.PlaySound("die.wav");
                GameStatus="lost";
                PacLostTime=System.currentTimeMillis();
            }
      }
    }
    //Ham kiem tra huong de ve pacman(ve trai, phai, tren, xuong)
    public static void AnimatePacMan(){
        PacAnimCounter += 1;
        if (PacAnimCounter>=1){
            PacAnimInd += PacAnimDir;
            if ((PacAnimInd >2) || (PacAnimInd < 0)){
                if (PacAnimDir==1){
                    PacAnimDir=-1;
                    PacAnimInd =2;
                }
                else{
                    PacAnimDir=1;
                    PacAnimInd = 0;
                }
            }
            PacAnimCounter=0;
        }    
    }
    
    public static boolean notCharKeys(char x){
        return (x!='1'||x!='2'||x!='3'||x!='4'||x!='A'||x!='B'||x!='C'||x!='D'||x!='$'||x!='#'||x!='R'||x!='@');
    }
    
    public static boolean charKeys(char x){
        return (x=='1'||x=='2'||x=='3'||x=='4'||x=='A'||x=='B'||x=='C'||x=='D'||x=='$'||x=='#'||x=='R');
    }
    //ham checkKey de di chuyen pacman
    public static void CheckKeys(){
        int XmodW=0,YmodH=0;
        int BoxX=0,BoxY=0;      
        XmodW=TOA_DO_HIEN_TAI_Px%24;
        YmodH=TOA_DO_HIEN_TAI_Py%24;
        if ((XmodW==0)&&(YmodH==0)){   
           BoxX=TOA_DO_HIEN_TAI_Px/24;
           BoxY=TOA_DO_HIEN_TAI_Py/24;    
           if (BoxX<0) { BoxX=0; }
           if (BoxY<0) { BoxY=0; }   
           if (NewKeydir==0){
                if (BoxX<19) {
                    if (notCharKeys(level[BoxX+1][BoxY])&&((level[BoxX+1][BoxY]!='@')||(level[BoxX+1][BoxY]!='&')))
                        Pdir=NewKeydir;
                }
           }
           else
           if (NewKeydir==2){
                if (BoxX>0)
                if (notCharKeys(level[BoxX-1][BoxY])&&((level[BoxX-1][BoxY]!='@')||(level[BoxX-1][BoxY]!='&')))
                    Pdir=NewKeydir;         
           }
           else
           if (NewKeydir==1){
                if (BoxY>0) 
                  if (notCharKeys(level[BoxX][BoxY-1])&&((level[BoxX][BoxY-1]!='@')||(level[BoxX][BoxY-1]!='&')))
                    Pdir=NewKeydir;
           }
           else
               if (NewKeydir==3){
                   if (BoxY<22)
                      if (notCharKeys(level[BoxX][BoxY+1])&&((level[BoxX][BoxY+1]!='@')||(level[BoxX][BoxY+1]!='&')))
                    Pdir=NewKeydir;
              }   
        }
        else{
               //di chuyen 180 do
               if (Pdir!=NewKeydir){
                   if (((NewKeydir==0) || (NewKeydir==2)) && (XmodW!=0) && (YmodH==0))
                       Pdir=NewKeydir;
                   if (((NewKeydir==1) || (NewKeydir==3)) && (YmodH!=0) && (XmodW==0) )
                       Pdir=NewKeydir;
               }
       }
    }
    //ham di chuyen pacman
    public static void MovePacman(){
        int XmodW=0,YmodH=0;
        int BoxX=0,BoxY=0;
        int x=0,y=0;
        int tmpx=0,tmpy=0;
        int ifcando=1;
        for (y=-2;y<3;y++)
            for (x=-2;x<3;x++){
                tmpx = (TOA_DO_HIEN_TAI_Px+(PmSpeed * x));
                tmpy = (TOA_DO_HIEN_TAI_Py+(PmSpeed * y));
                XmodW=tmpx % 24;
                YmodH=tmpy % 24;
                if ((XmodW==0) && (YmodH==0)){
                    BoxX = tmpx  / 24;
                    BoxY = tmpy  / 24;
                    if ( level[BoxX][BoxY]=='.'){//neu an  thi gan cho toa do do la rong
                        level[BoxX][BoxY] = '-';
                        Score+= 20; // tang diem so
                        Sound.PlaySound("eatdot.wav");
                    }
                    if ( level[BoxX][BoxY]=='O'){//neu an vien ngoc thi gan cho toa do do la rong
                        level[9][13] = 'V';
                        level[BoxX][BoxY]='-';
                        //level[][24*8]='V';
                        Score+= 100; // khi an duoc vien ngoc thi se cong 50 diem
                        Sound.PlaySound("eatdot.wav");
                        //Super mode
                        Pac_going_super=1;
                    }
                    if (level[BoxX][BoxY]=='V'){
                        level[BoxX][BoxY]='-';
                        Score+= 200;
                        Sound.PlaySound("eatdot.wav");
                    }
                    
                }
            }
        XmodW=TOA_DO_HIEN_TAI_Px % 24;
        YmodH=TOA_DO_HIEN_TAI_Py % 24;
        if (XmodW==0){
            if (YmodH==0){
                BoxX = TOA_DO_HIEN_TAI_Px  /24;
                BoxY = TOA_DO_HIEN_TAI_Py  /24;
                if (BoxX < 0) { BoxX=0; }
                if (BoxY < 0) { BoxY=0; }
                if (Pdir==0){
                    if (BoxX<18){
                        if (charKeys(level[BoxX+1][BoxY])&&(level[BoxX+1][BoxY]!='@')&&(level[BoxX+1][BoxY]!='&'))
                            ifcando=0;
                    }
                    else
                        TOA_DO_HIEN_TAI_Px= 0;
                }
                else
                if (Pdir==2){
                    if (BoxX>0){
                        if (charKeys(level[BoxX-1][BoxY])&&(level[BoxX-1][BoxY]!='@')&&(level[BoxX-1][BoxY]!='&'))
                            ifcando=0;
                    }
                    else
                        TOA_DO_HIEN_TAI_Px= 18* 24;
                }     
                else
                if (Pdir==1){
                    if (BoxY>0){
                        if (charKeys(level[BoxX][BoxY-1])&&(level[BoxX][BoxY-1]!='@')&&(level[BoxX][BoxY-1]!='&'))
                            ifcando=0;
                    }
                    else
                        TOA_DO_HIEN_TAI_Py= 0;
                }
                else
                if (Pdir==3){
                    if (BoxY<21){
                        if (charKeys(level[BoxX][BoxY+1])&&(level[BoxX][BoxY+1]!='@')&&(level[BoxX][BoxY+1]!='&'))
                            ifcando=0;
                    }
                    else
                        TOA_DO_HIEN_TAI_Py= 21*24;
                }
            SpeedFix();
           }
        }
       if (ifcando==1){
            if (Pdir==1)
                TOA_DO_HIEN_TAI_Py -= PmSpeed;//len tren
            else
            if (Pdir==3)
                TOA_DO_HIEN_TAI_Py += PmSpeed;//xuong
            else
            if (Pdir==0)
                TOA_DO_HIEN_TAI_Px += PmSpeed;//sang phai
            else
            if (Pdir==2)
                TOA_DO_HIEN_TAI_Px -= PmSpeed;//sang trai
       }    
    }
    public static void SpeedFix(){
        int x=0,y=0;
        char cByte;
        tmpDotCnt=SoVatPham;
        //an diem
        for(y=0;y<22;y++) {
            for(x=0;x<19;x++){
                  cByte=level[x][y];    
                  if ((cByte=='.') || (cByte=='O'))
                      tmpDotCnt -= 1;
             }
        }
         if (Pac_going_super==1){//khi an duoc vien ngoc thi thay doi van toc pacman
             //tang toc do cho pacman
             Pac_going_super=0;
             PmSpeed=PacSuperSpeed;
             PacisSuper=1;
             PacSuperTime=System.currentTimeMillis();
             anNgoc=true;
             GhostRecoveryChange=0;
             level[DoorX][DoorY]='@';
             level[9][13]='V';
             Sound.player.setTempoFactor((float)1.2);
         }
         else{
             if (((tmpDotCnt*100/SoVatPham)>60)&&(PacisSuper==0))
                   PmSpeed=PacSuperSpeed;
             else{
                 if (System.currentTimeMillis()-PacSuperTime>7000){
                    PacisSuper=0;
                    PmSpeed=PacNormalSpeed;
                 }
            }
         }
         if (System.currentTimeMillis()-PacSuperTime>7000){
                anNgoc=false;
                Sound.player.setTempoFactor((float)1.0);
                level[DoorX][DoorY]='&';
                SO_GHOST_AN=0;
        }           
        if (tmpDotCnt==SoVatPham){
            Diemso.NewHighScore(Score,HighScore);
            Khoitao();
            setupGhosts();
            GameStatus="won";
        }
    } 
    
    //Di chuyen ghost
    public static void MoveGhosts(){
        int XmodW=0,YmodH=0;
        int BoxX=0,BoxY=0;
        int ind=0,n=0,tmpi=0,PboxX,PboxY;
        boolean UPblocked,DOWNblocked,LEFTblocked,RIGHTblocked;
        for(ind=0;ind<4;ind++){
            UPblocked=false;
            DOWNblocked=false;
            LEFTblocked=false;
            RIGHTblocked=false;
            XmodW=GhostX[ind] % 24;
            YmodH=GhostY[ind] % 24;  
            if (XmodW==0){
                if (YmodH==0){               
                    BoxX = GhostX[ind]  / 24;
                    BoxY = GhostY[ind]  / 24;
                    if (BoxX<0){ BoxX=0; }
                    if (BoxY<0){ BoxY=0; }
                    if (BoxX<18){
                        if (charKeys(level[BoxX+1][BoxY])||(level[BoxX+1][BoxY]=='@'))
                            RIGHTblocked=true;
                        else {}
                    }
                    else{RIGHTblocked=true;}
                    if (BoxX>0){
                        if (charKeys(level[BoxX-1][BoxY])||(level[BoxX-1][BoxY]=='@'))
                            LEFTblocked=true;
                        else {}
                    }else{LEFTblocked=true;}
                    if (BoxY>0){
                        if (charKeys(level[BoxX][BoxY-1])||(level[BoxX][BoxY-1]=='@'))
                            UPblocked=true;
                        else {}
                    }else{UPblocked=true;}
                    if (BoxY<21){
                        if (charKeys(level[BoxX][BoxY+1])||(level[BoxX][BoxY+1]=='@'))
                            DOWNblocked=true;
                         else {}
                    }else {DOWNblocked=true;}
                    int tmpr=0,newDir=0;
                    tmpr = (int)(Math.random()*10);
                    tmpr = (int)(Math.random()*10);
                    tmpr = (int)(Math.random()*21);
                    while (newDir==0){
                        if ((tmpr>50) || (tmpr<-50))
                        tmpr = (int)(Math.random()*11);
                        if (RIGHTblocked==false)
                        if((GhostDir[ind]!=2)||(tmpr<-10))
                            if(tmpr<1){
                                GhostDir[ind]=0;
                                tmpr=100;
                                newDir=1;
                            }
                            else{tmpr -= 1;}
                        else 
                            {tmpr -= (int)(Math.random()*3);} 
                        
                        if (LEFTblocked==false) {
                            if((GhostDir[ind]!=0)||(tmpr<-10))
                                if(tmpr<1){
                                    GhostDir[ind]=2;
                                    tmpr=100;
                                    newDir=1;
                                }else{tmpr -= 1;}
                        }else{tmpr -= (int)(Math.random()*3);}
                        
                        if (DOWNblocked==false) {
                            if((GhostDir[ind]!=1) || (tmpr<-10))
                                if(tmpr<1){
                                    GhostDir[ind]=3;
                                    tmpr=100;
                                    newDir=1;
                                }else{tmpr -= 1;}
                        }else{tmpr -= 1;}

                        if (UPblocked==false) {
                            if((GhostDir[ind]!=3) || (tmpr<-10))
                                if(tmpr<1){
                                    GhostDir[ind]=1;
                                    tmpr=100;
                                    newDir=1;
                                } else {tmpr -= 1;}
                        } else {tmpr -= (int)(Math.random()*2);}
                        tmpr -= (int)(Math.random()*2);
                    }
                    PboxX = TOA_DO_HIEN_TAI_Px  / 24;
                    PboxY = TOA_DO_HIEN_TAI_Py  / 24;     
                    tmpi=0;
                    for(n=BoxX;n<19;n++)
                        if (tmpi==0)
                            if (charKeys(level[n][BoxY]))
                                tmpi=1;
                            else{
                                if((n==PboxX)&&(PboxY==BoxY)){
                                    if(anNgoc==true){
                                        if (UPblocked==false){GhostDir[ind]=1;}
                                        if (DOWNblocked==false){GhostDir[ind]=3;}
                                        if (LEFTblocked==false){GhostDir[ind]=2;}
                                    }else
                                        GhostDir[ind]=0;
                                }
                            }
                     tmpi=0;
                     for(n=BoxX;n>0;n--) {
                        if (tmpi==0)
                            if (charKeys(level[n][BoxY]))
                                tmpi=1;
                            else{
                                if((n==PboxX)&&(PboxY==BoxY)){
                                    if(anNgoc==true){
                                        if (UPblocked==false){GhostDir[ind]=1;}
                                        if (DOWNblocked==false){GhostDir[ind]=3;}
                                        if (RIGHTblocked==false){GhostDir[ind]=0;}
                                    }else
                                        GhostDir[ind]=2;
                                }
                           }
                    }
                    tmpi=0;
                    for(n=BoxY;n>0;n--)
                        if (tmpi==0)
                            if (charKeys(level[BoxX][n]))
                                tmpi=1;
                            else{
                                if((n==PboxY)&&(PboxX==BoxX)){
                                    if(anNgoc==true){
                                        if (LEFTblocked==false){GhostDir[ind]=2;}
                                        if (RIGHTblocked==false){GhostDir[ind]=0;}
                                        if (DOWNblocked==false){GhostDir[ind]=3;}
                                    }else
                                        GhostDir[ind]=1;
                                }
                            }
                    tmpi=0;
                    for(n=BoxY;n<22;n++)
                        if (tmpi==0)
                            if (charKeys(level[BoxX][n]))
                                tmpi=1;
                            else{
                                if((n==PboxY)&&(PboxX==BoxX)){
                                    if(anNgoc==true){
                                        if (LEFTblocked==false){GhostDir[ind]=2;}
                                        if (RIGHTblocked==false){GhostDir[ind]=0;}
                                        if (UPblocked==false){GhostDir[ind]=1;}
                                    }else
                                        GhostDir[ind]=3;    
                                }
                            }
                }
            }
            if (GhostDir[ind]==1){
                GhostY[ind] -= 2;
            }
            if (GhostDir[ind]==3){
                GhostY[ind] += 2;
            }
            if (GhostDir[ind]==0){
                GhostX[ind] += 2;
            }
            if (GhostDir[ind]==2){
                GhostX[ind] -= 2;
            }
        }       
    }   
    
    //load anh
    public void LoadGraphics(){
        int ind=0,anim=0,tmpi=0,n=0,n2=0;
        PAC_IMG = new Image[4][3];
        for (ind=0;ind<4;ind++) {
            for (anim=0;anim<=2;anim++)
                PAC_IMG[ind][anim] =new ImageIcon("src/Data/Pac" + String.valueOf(ind) + String.valueOf(anim) + ".gif").getImage();
        }
        NEW_GAME_IMG = new Image[3];
        NEW_GAME_IMG[0] = new ImageIcon("src/Data/newgamenormal.gif").getImage();
        NEW_GAME_IMG[1] = new ImageIcon("src/Data/newgameover.gif").getImage();
        NEW_GAME_IMG[2] = new ImageIcon("src/Data/newgameclicked.gif").getImage();
        WonImg     =  new ImageIcon("src/Data/wonmsg.png").getImage();
        LostImg    =  new ImageIcon("src/Data/lostmsg.png").getImage();
        PausedImg  =  new ImageIcon("src/Data/paused.png").getImage();
        GameOverImg=  new ImageIcon("src/Data/gameoverpanel.png").getImage();
        DoorImg    =  new ImageIcon("src/Data/door.jpg").getImage();
        GHOST_IMG   = new Image[4][2][4];
        SCARED_GHOST = new Image[2];
        SCARED_GHOST_RECOVERY = new Image[2];
        VAT_PHAM=new ImageIcon("src/Data/dauTay.png").getImage();
        tmpi=1;
        for(ind=0;ind<4;ind++){
            tmpi -= 1;
            if (tmpi<1){tmpi=1;}
            for(n=0;n<2;n++){
                n2=n+1;
                GHOST_IMG[ind][n][0]= new ImageIcon("src/Data/ghost" + tmpi + "-" + n2 + "-0.gif").getImage();
                GHOST_IMG[ind][n][1]= new ImageIcon("src/Data/ghost" + tmpi + "-" + n2 + "-1.gif").getImage();
                GHOST_IMG[ind][n][2]= new ImageIcon("src/Data/ghost" + tmpi + "-" + n2 + "-2.gif").getImage();
                GHOST_IMG[ind][n][3]= new ImageIcon("src/Data/ghost" + tmpi + "-" + n2 + "-3.gif").getImage();
            }
        }
        SCARED_GHOST[0] =  new ImageIcon("src/Data/scaredghost1.gif").getImage();
        SCARED_GHOST[1] =  new ImageIcon("src/Data/scaredghost2.gif").getImage();
        SCARED_GHOST_RECOVERY[0] =  new ImageIcon("src/Data/scaredghostrecovery1.gif").getImage();
        SCARED_GHOST_RECOVERY[1] =  new ImageIcon("src/Data/scaredghostrecovery2.gif").getImage();
        //wallimg = new ImageIcon("src/Data/wall.jpg").getImage();
        wallImgColum = new ImageIcon("src/Data/wall_col.png").getImage();
        wallImgRow = new ImageIcon("src/Data/wall_row.png").getImage();
        wallImgAngleA = new ImageIcon("src/Data/wall_angleA.png").getImage();
        wallImgAngleB = new ImageIcon("src/Data/wall_angleB.png").getImage();
        wallImgAngleC = new ImageIcon("src/Data/wall_angleC.png").getImage();
        wallImgAngleD = new ImageIcon("src/Data/wall_angleD.png").getImage();
        wallImgAngleRA = new ImageIcon("src/Data/wall_angleRA.png").getImage();
        wallImgAngleRB = new ImageIcon("src/Data/wall_angleRB.png").getImage();
        wallImgAngleRC = new ImageIcon("src/Data/wall_angleRC.png").getImage();
        wallImgAngleRD = new ImageIcon("src/Data/wall_angleRD.png").getImage();
        wallImgAngleR = new ImageIcon("src/Data/wall_angleR.png").getImage();
        scaredWallImg = new ImageIcon("src/Data/scaredwall.png").getImage();
        backroundImg = new ImageIcon("src/Data/backround.jpg").getImage();
    }
    //khoi dong am thanh
    public static void StartMusic(){
         try{
            int tmpr=0;
            tmpr = (int)(Math.random()*14) + 1;
            File sf = new File("src//Data//" + String.valueOf(tmpr) + ".x");
            Sound.player = MidiSystem.getSequencer();
            Sequence song = MidiSystem.getSequence(sf);
            Sound.player.open();
            Sound.player.setSequence(song);
            Sound.player.setLoopCount(0);
            Sound.player.start();            
        } catch (Exception e) {System.out.println(e.toString());}
    }
    //Load Map
    public static void LoadMap(){
        int toByte;
        int x=0,y=0,ByteCheck=0;
        char cByte;   
        level = new char[20][23];
        try {
            FileReader levelFile = new FileReader("src/Data/level1.txt");
            FileReader levelFile1 = new FileReader("src/Data/level0.txt");
            if (DIEM_LEVEL>0)
                levelFile=levelFile1;
            SoVatPham=0;
            for(y=0;y<=22;y++){
                for(x=0;x<19;x++){
                    if (ByteCheck!=3){
                        do{
                            ByteCheck=0;
                            toByte = levelFile.read(); 
                            if ((toByte==13)||(toByte==10)) ByteCheck=1;
                            if (toByte==-1)ByteCheck=3;
                        } while(ByteCheck==1); 
                        cByte = (char)toByte;        
                        if (ByteCheck!=3){
                            level[x][y]=cByte;
                            if ((cByte=='.')||(cByte=='O'))
                                SoVatPham += 1;
                        }
                    }
               }
          }
      }
      catch(IOException e){
         System.out.println("IO Exception : " + e.toString());
     }
    }
}

